#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import model
import urllib
from lib.loggable import loggable

import app_params as application_params

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

__SESSION_ID = application_params.Http.SESSION_ID

def roles(roles = {}):
  """Requires that a user is logged in and has a role specified as the argument."""   
  
  def login_required(handler):

      @loggable('check_login')
      def check_login(self,*args):
        try:
          session_id = self.request.cookies[__SESSION_ID]
        except KeyError:
          session_id = None
        if session_id is None:
          logging.debug('session id is none - redirecting to main page')
          self.redirect('/?continue_to=' + urllib.quote_plus(self.request.url))
          return
        session = model.Session.all().filter('id = ', session_id).get()
        if session is None:
          logging.debug('session found but could not be retrieved from the database')
          self.response.headers.add_header('set-cookie', application_params.Http.SESSION_ID + '=')
          logging.debug('deleting session cookie')
          self.redirect('/?continue_to=' + urllib.quote_plus(self.request.url))
          return
        if session.user is None:
          raise AuthError('session present but no user associated')
        logging.debug('user found and associated with an existing user')
        self.session = session
        self.user = session.user
        logging.debug('user has been logged in successfully')
        handler(self,*args)
        
      return check_login
  return login_required


def login_required(handler):
    """Requires that a user is logged in to be able to execute a method."""    

    @loggable('check_login')
    def check_login(self,*args):
      try:
        session_id = self.request.cookies[__SESSION_ID]
      except KeyError:
        session_id = None
      if session_id is None:
        logging.debug('session id is none - redirecting to main page')
        self.redirect('/?continue_to=' + urllib.quote_plus(self.request.url))
        return
      session = model.Session.all().filter('id = ', session_id).get()
      if session is None:
        logging.debug('session found but could not be retrieved from the database')
        self.response.headers.add_header('set-cookie', application_params.Http.SESSION_ID + '=')
        logging.debug('deleting session cookie')        
        self.redirect('/?continue_to=' + urllib.quote_plus(self.request.url))
        return
      if session.user is None:
          raise AuthError('session present but no user associated')
      logging.debug('user found and associated with an existing user')
      self.session = session
      self.user = session.user
      logging.debug('user has been logged in successfully')
      handler(self,*args)
      
    return check_login

 
def redirect_logged_user(location = '/'):
  
  def inner_redirect(handler):

      @loggable('redirect logged user')    
      def check_user_status(self,*args):
        try:
          session_id = self.request.cookies[__SESSION_ID]
        except KeyError:
          session_id = None
        if session_id:
          logging.debug('session id: %s' % session_id)
          session = model.Session.all().filter('id = ', session_id).get()
          if session: 
              logging.debug('session for user %s' % session.user)
              self.session = session
              self.user = session.user
              self.redirect(location)
              return
          logging.debug('session could not be retrieved from the DB')
          self.response.headers.add_header('set-cookie', application_params.Http.SESSION_ID + '=')
          logging.debug('deleting session cookie')          
        handler(self,*args)
      
      return check_user_status
    
  return inner_redirect

class AuthError(Exception):
    """Raised when there is an error with with the authentication process."""
    
    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return repr(self.msg) 
    
if __name__ == '__main__':
    pass